<script setup>
import { reactive, ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router"
import request from '@/api/request'
import { Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue'

let router = useRouter();
const rules = reactive({})



let columns = [
    { id: "materialId", label: "物料编码" },
    { id: "materialName", label: "物料名称" },
    { id: "specificationsAndModels", label: "规格型号" },
    { id: "unit", label: "单位" },
    { id: "materialOrProduct", label: "物料/产品" },
    { id: "category", label: "所属分类" }
]

let isdisabled = ref(true)
let isdisabledreove = ref(true)
let isVisible = ref(false)
let data=ref({})
let title = ref("")

let customerId = ref([])

let page = ref({
    current: 1,
    size: 5,
    total: 0,
    records: []
})

let Material = ref({
    materialId: '',
    materialName: ''
})

// 搜索
const handleSearch = () => {
    page.value.current = 1; // 搜索时重置到第一页
    loadData();
    console.log(page.value);
    
}

let loadData = () => { // 加载数据
    request({
        url: '/material/index',
        method: 'get',
        params: {
            current: page.value.current, // 当前页
            size: page.value.size, // 每页条数
            materialId: Material.value.materialId, // 直接传递物料编码
            materialName: Material.value.materialName // 直接传递物料名称
        }
    }).then(res => {
        page.value = res.data // 更新分页数据
    })
}

loadData();

let refTanle = () => {
    isVisible.value = false;
    loadData(); // 刷新表格
}
let toInsert = () => {
    title.value = "新增物料/产品";
    isVisible.value = true;
    router.push("/material/main/insert");
}

// let toUpdate = () => {
//     title.value = "修改物料/产品";
//     isVisible.value = true;
//     data.value = shipment_history_id.value;
//     router.push("/material/main/update");
// }
let toUpdate = async(row)=>{
     // 打开修改对话框
    data.value = row; // 设置要修改的数据
    
    title.value = "修改物料/产品";
    isVisible.value = true;
     router.push("/material/main/update");

} 
let toRemove = (materialId) =>{
    request({
        url:"/material/delete",
        method:"delete",
        data:materialId
    }).then(res=>{
        loadData()
    })
    
}


let shipment_history_id = ref([])

let fuxuankuang = (a) => {
    shipment_history_id.value = a.map(b => b.id)
    if (shipment_history_id.value.length == 1) {
        isdisabled.value = false;
        isdisabledreove.value = false;
    }
    if (shipment_history_id.value.length > 1) {
        isdisabled.value = true;
        isdisabledreove.value = false;
    }
    if (shipment_history_id.value.length == 0) {
        isdisabled.value = true;
        isdisabledreove.value = true;
    }
}

const shuju = ref([
    {
        id: 1,
        label: '物料产品分类',
        children: [
            {
                id: 2,
                label: '产品',
                children: [
                    {
                        id: 4,
                        label: '完成品',
                        children: [
                            { id: 8, label: '电脑' },
                            { id: 9, label: '鼠标' },
                            { id: 10, label: '键盘' }
                        ]
                    },
                    {
                        id: 5,
                        label: '半成品',
                        children: [
                            { id: 11, label: '方便面' },
                            { id: 12, label: '火锅底料' },
                            { id: 13, label: '预制菜' }
                        ]
                    },
                ],
            },
            {
                id: 3,
                label: '物料',
                children: [
                    {
                        id: 6,
                        label: '可食用物料',
                        children: [
                            { id: 14, label: '小鱼干' },
                            { id: 15, label: '调料包' },
                            { id: 16, label: '面饼' }
                        ]
                    },
                    {
                        id: 7,
                        label: '非可食用物料',
                        children: [
                            { id: 17, label: '螺丝' },
                            { id: 18, label: '螺帽' },
                            { id: 19, label: '袋子' }
                        ]
                    },
                ],
            },
        ],
    },
])

const defaultProps = {
    children: 'children',
    label: 'label',
}

const filterText = ref('')
const treeRef = ref()

// 展开所有节点的方法
const expandAllNodes = () => {
  const tree = treeRef.value
  if (tree) {
    const allNodes = tree.store._getAllNodes()
    allNodes.forEach(node => {
      node.expanded = true
    })
  }
}

// 组件挂载时展开所有节点
onMounted(() => {
  expandAllNodes()
})

// 改进的过滤方法 - 展示匹配节点、其父节点和同级节点
const filterNode = (value, data, node) => {
    if (!value) return true
    
    // 如果当前节点匹配
    if (data.label.includes(value)) {
        // 展开所有父节点和同级节点
        expandParentsAndSiblings(node)
        return true
    }
    
    // 检查是否是匹配节点的父节点或同级节点
    return isParentOrSiblingOfMatch(node, value)
}

// 展开父节点和同级节点
const expandParentsAndSiblings = (node) => {
    // 展开所有父节点
    let parent = node.parent
    while (parent) {
        parent.expanded = true
        parent = parent.parent
    }
    
    // 展开同级节点
    if (node.parent) {
        node.parent.childNodes.forEach(child => {
            child.expanded = true
        })
    }
}

// 检查是否是匹配节点的父节点或同级节点
const isParentOrSiblingOfMatch = (node, value) => {
    // 检查是否是父节点
    if (node.childNodes) {
        for (const child of node.childNodes) {
            if (child.data?.label.includes(value)) {
                return true
            }
        }
    }
    
    // 检查是否是同级节点
    if (node.parent) {
        for (const sibling of node.parent.childNodes) {
            if (sibling.data?.label.includes(value)) {
                return true
            }
        }
    }
    
    return false
}

// 监听过滤文本变化
watch(filterText, (val) => {
    treeRef.value.filter(val)
    
    if (val) {
        const tree = treeRef.value
        const allNodes = tree.store._getAllNodes()
        
        // 先收起所有节点
        allNodes.forEach(node => {
            node.expanded = false
        })
        
        // 展开匹配节点及其父节点和同级节点
        allNodes.forEach(node => {
            if (node.data?.label.includes(val)) {
                expandParentsAndSiblings(node)
            }
        })
    } else {
        // 清空搜索时重新展开所有节点
        expandAllNodes()
    }
})

let formRef = ref()

// 重置
let chongzhi = () => {
    Material.value = {
        materialId: '',
        materialName: ''
    }
    filterText.value = ''
    expandAllNodes()
    handleSearch() // 重置后立即搜索
}

const formData = ref({
    materialName: '',
})


const handleAddSuccess = (newMaterial) => {
    // 添加到表格数据的最前面
    page.value.records.unshift({
        id: Date.now(), // 使用时间戳作为临时ID
        materialId: newMaterial.Material_id,
        materialName: newMaterial.Material_name,
        specificationsAndModels: newMaterial.SpecificationsAndModels,
        unit: newMaterial.unit,
        materialOrProduct: newMaterial.Category === 'wl' ? '物料' : '产品',
        category: newMaterial.Category === 'wl' ? '物料' : '产品'
    })
    // 更新总条数
    page.value.total += 1
    // 关闭对话框
    isVisible.value = false
    // 显示成功提示
    ElMessage.success('新增成功')
}

// let remove =()=>{
//     request({
//         url:'material/remove',
//         method
//     })
// }


</script>

<template>
    <div>
        <el-card>
            <template #header>
                <div >
                    <el-row>
                        <el-col :span="6">
                            <el-input 
                                v-model="filterText" 
                                placeholder="输入关键字过滤分类" 
                                size="large" 
                                clearable 
                                style="margin-bottom: 10px;"
                            />
                            
                            <el-tree
                                ref="treeRef"
                                class="filter-tree"
                                :data="shuju"
                                :props="defaultProps"
                                :filter-node-method="filterNode"
                                node-key="id"
                                highlight-current
                                @node-click="(data) => { formData.materialName = data.label }"
                            >
                                <template #default="{ node }">
                                    <span>{{ node.label }}</span>
                                </template>
                            </el-tree>
                        </el-col>

                        <el-col :span="18">
                            <el-form ref="formRef" inline :model="Material"
                                style="display: flex;justify-content: start;" class="card_wrap">
                                <el-form-item label="物料编码" size="default" prop="materialId" class="c_item">
                                    <el-input v-model="Material.materialId" class="sousuo"
                                        placeholder="请输入物料编码" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item label="物料名称" size="default" prop="materialName" class="c_item">
                                    <el-input v-model="Material.materialName" class="sousuo"
                                        placeholder="请输入物料名称" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item class="c_item">
                                    <template #default>
                                        <el-button type="primary" size="default" @click="handleSearch" icon="Search">搜索</el-button>
                                        <el-button type="info" size="default" :plain=true @click="chongzhi" icon="Refresh">重置</el-button>
                                    </template>
                                </el-form-item>
                            </el-form>

                            <div style="margin-top: 20px;">
                                <el-button @click="toInsert" type="primary" :plain="true" icon="Plus">添加</el-button>
                                <el-button type="success" size="default" :plain=true @click="toUpdate" icon="Plus" style="border:0px"
                                   :disabled=isdisabled >修改</el-button>
                                <el-button type="danger" size="default" :plain=true @click="toRemove" icon="Delete" style="border:0px"
                                    :disabled=isdisabledreove>删除</el-button>
                            </div>

                            <el-table :data="page.records" border stripe @selection-change="fuxuankuang">
                                <el-table-column type="selection" width="55" />
                                <el-table-column v-for="col in columns" :prop="col.id" :key="col.id" :label="col.label">
                                </el-table-column>
                            <el-table-column label="操作" fixed="right" width="200px">
                                <template #default="scope"style="width: 1000px;">
                                    <el-button size="small" type="primary" @click="toUpdate(scope.row)" icon="Plus" :row="scope.row">修改</el-button>
                                    <el-button size="small" type="danger" @click="toRemove(scope.row.materialId)" icon="Delete">删除</el-button>
                                </template>
                            </el-table-column>
                            </el-table>
                            <el-pagination @current-change="loadData" v-model:currentPage="page.current"
                        :page-sizes="[2, 4, 6, 8, 10]" :page-size="page.size" :total="page.total" background>
                        </el-pagination>
                        </el-col>
                    </el-row>
                    <div style="width:800px">
                        <el-dialog :title="title" v-model="isVisible" :destroy-on-close="true" width="60%">
                            <router-view @ref-table="refTanle":data="data">
                            </router-view>
                        </el-dialog>
                    </div>
                </div>
            </template>
        </el-card>
    </div>
</template>

<style scoped>
.sousuo {
    width: 200px;
}

.card_wrap {
    width: 98%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.c_item {
    flex: 1;
    margin: 0px 5px 15px 0;
    width: calc((100%-10px)/3);
    min-width: calc((100% - 10px)/3);
    max-width: calc((100% - 10px)/3);

    &:nth-child(3n) {
        margin-right: 0;
    }
}

.filter-tree :deep(.el-tree-node__content) {
    height: auto;
    padding: 5px 0;
}
</style>